<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="动态规划基础：爬楼梯和挖金矿问题, 湮灭星空,博客,Python,后端">
    <meta name="description" content="动态规划基础：爬楼梯和挖金矿问题
三核心

最优子结构
边界
状态转移方程

问题 1
有一座高度是 10 级台阶的楼梯，从下往上走，每跨一步只能向上 1 级或者2 级台阶。要求使用程序来求出一共有多少种走法？
方法 1
逆向思维：
要走到">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <title>动态规划基础：爬楼梯和挖金矿问题 | 湮灭星空</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<link rel="alternate" href="/atom.xml" title="湮灭星空" type="application/atom+xml">
</head>

<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper head-container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">湮灭星空</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友链</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>

<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">湮灭星空</div>
        <div class="logo-desc">
            
            天下寥寥，苍生涂涂，诸子百家，唯我纵横
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友链
		</a>
          
        </li>
        
        
    </ul>
</div>

        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/4.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <div class="description center-align post-title">
                        动态规划基础：爬楼梯和挖金矿问题
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #toc-content .is-active-link::before {
        background-color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/markdown/">
                                <span class="chip bg-color">markdown</span>
                            </a>
                        
                            <a href="/tags/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/">
                                <span class="chip bg-color">动态规划</span>
                            </a>
                        
                            <a href="/tags/%E7%AE%97%E6%B3%95/">
                                <span class="chip bg-color">算法</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/Tech/" class="post-category">
                                Tech
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2019-11-19
                </div>
                

                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-check fa-fw"></i>更新日期:&nbsp;&nbsp;
                    2020-01-30
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    2.8k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    11 分
                </div>
                
				
                
                    <div id="busuanzi_container_page_pv" class="info-break-policy">
                        <i class="far fa-eye fa-fw"></i>阅读次数:&nbsp;&nbsp;
                        <span id="busuanzi_value_page_pv"></span>
                    </div>
				
            </div>
            
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <h1 id="动态规划基础：爬楼梯和挖金矿问题"><a class="header-anchor" href="#动态规划基础：爬楼梯和挖金矿问题"></a>动态规划基础：爬楼梯和挖金矿问题</h1>
<h2 id="三核心"><a class="header-anchor" href="#三核心"></a>三核心</h2>
<ul>
<li>最优子结构</li>
<li>边界</li>
<li>状态转移方程</li>
</ul>
<h2 id="问题-1"><a class="header-anchor" href="#问题-1"></a>问题 1</h2>
<p>有一座高度是 10 级台阶的楼梯，从下往上走，每跨一步只能向上 1 级或者2 级台阶。要求使用程序来求出一共有多少种走法？</p>
<h3 id="方法-1"><a class="header-anchor" href="#方法-1"></a>方法 1</h3>
<p>逆向思维：</p>
<p>要走到 10 级，可以从 9 级走1 级上或者从 8 级走2 级上。如果到 9 级有 X 中方法，到 8 级有 Y 种方法，那么到 10 级就有 X+Y 种方法。由此可见，到 N 级的方法数为到 N-1 级和到 N-2 级方法数的总和，假设使用 F(N) 表示到 N 级的方法数，那么</p>
<pre><code class="language-python">F(N) = F(N-1) + F(N-2)
</code></pre>
<p>显然</p>
<pre><code class="language-python">F(1) = 1
F(2) = 2
</code></pre>
<p>显然代码很简单：</p>
<pre><code class="language-python">def F(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    elif n == 2:
        return 2
    else:
        return F(n - 1) + F(n - 2)
</code></pre>
<h4 id="时间复杂度"><a class="header-anchor" href="#时间复杂度"></a>时间复杂度</h4>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-11-18-081553.png" alt="image-20191118161552644"></p>
<p>要计算F(n)必须先计算 F(n-1)和 F(n-2)，以此类推，可以归纳成上面的图，完全就是一个二叉树。很容易看出二叉树的高度为 n-1，节点数接近 $2^{n-1}$，所以时间复杂度可以近似的看成 $O(2^n)$</p>
<h4 id="优化"><a class="header-anchor" href="#优化"></a>优化</h4>
<p>回顾一下刚才的递归图，有一些相同的参数被重复计算了，越往下走，重复的越多。</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-11-18-082624.png" alt="image-20191118162623950"></p>
<p>如图所示，如果相同的颜色表示方法被传入了相同的参数，重复的就很多。</p>
<h3 id="备忘录算法"><a class="header-anchor" href="#备忘录算法"></a>备忘录算法</h3>
<p>可以使用缓存的设计来避免重复计算。可以建立一个哈希表，每次把不同参数的计算结果存入哈希。当遇到相同参数时，就从哈希表取结果。</p>
<pre><code class="language-python">map = {}


def F(n):
    global map
    if n == 0:
        return 0
    elif n == 1:
        return 1
    elif n == 2:
        return 2
    else:
        if n in map.keys():
            return map.get(n)
        else:
            result = F(n - 1) + F(n - 2)
            map.update({n: result})
            return result
</code></pre>
<p>以上代码中，map 是一个备忘录。当每次需要计算 F(n)的时候，会先从 map 中寻找匹配元素。如果map 中存在，就直接返回结果，如果 map 中不存在，就计算出结果，存入备忘录。</p>
<h4 id="时间复杂度"><a class="header-anchor" href="#时间复杂度"></a>时间复杂度</h4>
<p>从 F(1)到 F(n)一共有 n 个不同的输入，在哈希表里共存了 n-2 个结果，所以时间复杂度和空间复杂度都是 $O(n)$</p>
<p>这还不是真正的动态规划，还能继续优化。</p>
<h3 id="最佳解法"><a class="header-anchor" href="#最佳解法"></a>最佳解法</h3>
<p>上面的算法是自顶向下的算法，可以使用自底向上迭代的方式来得出结果。</p>
<p>上面 map 里面保存了一连串的键值对，实际上，每次求 n 的时候只与 n-1 、n-2 有关，所以我们只需要保存 n-1、n-2 的结果就可以了，我们只使用两个变量。每次计算完之后更新这两个变量的值，就可以得到下一个结果，代码如下：</p>
<pre><code class="language-python">def F(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    elif n == 2:
        return 2
    else:
        a = 1
        b = 2
        for i in range(3, n):
            a, b = b, a + b
        return a + b
</code></pre>
<p>程序从 i=3 开始迭代，一直到 i=n 结束。每一次迭代，都会计算出多一级台阶的走法数量。迭代过程中只需要保留两个临时变量a 和 b，分别代表了上一次和上上次迭代的结果。</p>
<h4 id="时间复杂度-o-n"><a class="header-anchor" href="#时间复杂度-o-n"></a>时间复杂度 $O(n)$</h4>
<h4 id="空间复杂度-o-1"><a class="header-anchor" href="#空间复杂度-o-1"></a>空间复杂度 $O(1)$</h4>
<h2 id="问题-2"><a class="header-anchor" href="#问题-2"></a>问题 2</h2>
<p>有一个国家发现了 5 座金矿，每座金矿的黄金储备量不同，需要挖坑的工人数也不同。参与挖矿工人的总数是 10 人。每座金矿要么全挖，要么不挖，不能派出一半人挖取一半金矿。要求用程序求解出，要想得到尽可能多的黄金，应该选择挖取哪几座金矿？</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-11-18-130825.png" alt="image-20191118182633628"></p>
<table>
<thead>
<tr>
<th>金矿名</th>
<th>矿产/金</th>
<th>用工数/人</th>
</tr>
</thead>
<tbody>
<tr>
<td>金矿 1</td>
<td>400</td>
<td>5</td>
</tr>
<tr>
<td>金矿 2</td>
<td>500</td>
<td>5</td>
</tr>
<tr>
<td>金矿 3</td>
<td>200</td>
<td>3</td>
</tr>
<tr>
<td>金矿 4</td>
<td>300</td>
<td>4</td>
</tr>
<tr>
<td>金矿 5</td>
<td>350</td>
<td>3</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>工人数</th>
<th>0人</th>
<th>1人</th>
<th>2人</th>
<th>3人</th>
<th>4人</th>
<th>5人</th>
<th>6人</th>
<th>7人</th>
<th>8人</th>
<th>9人</th>
<th>10人</th>
</tr>
</thead>
<tbody>
<tr>
<td>金矿 1</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>400</td>
<td>400</td>
<td>400</td>
<td>400</td>
<td>400</td>
<td>400</td>
</tr>
<tr>
<td>金矿 2</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>500</td>
<td>500</td>
<td>500</td>
<td>500</td>
<td>500</td>
<td>900</td>
</tr>
<tr>
<td>金矿 3</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>200</td>
<td>200</td>
<td>500</td>
<td>500</td>
<td>500</td>
<td>700</td>
<td>700</td>
<td>900</td>
</tr>
<tr>
<td>金矿 4</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>200</td>
<td>300</td>
<td>500</td>
<td>500</td>
<td>500</td>
<td>700</td>
<td>800</td>
<td>900</td>
</tr>
<tr>
<td>金矿 5</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>350</td>
<td>350</td>
<td>500</td>
<td>550</td>
<td>650</td>
<td>850</td>
<td>850</td>
<td>900</td>
</tr>
</tbody>
</table>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-11-18-130717.png" alt="image-20191118210717347"></p>
<p>也是动态规划的思路，有 5 座金矿，假如前面 4 座先不管，就看第 5 座，那就有两种情况：</p>
<ul>
<li>不挖：前 4 座分配 10 个人挖，获取最大黄金量</li>
<li>挖：前面 4 座分配 10-3 个人挖，获取的黄金量 = 挖前 4 座获取的黄金量 + 350 金</li>
</ul>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-11-18-131320.png" alt="image-20191118211320413"></p>
<p>显然上图显示了本问题的最优子结构。接下来就是分析最优子结构与最终问题的关系：4 座金矿的最优选择与 5 座金矿的最优选择之间的关系？</p>
<p>显然 5 座金矿获取的黄金量有两种算法：</p>
<ul>
<li>4 座金矿 10 个人的最优选择</li>
<li>4 座金矿 7 个人的最优选择 + 第 5 座金矿的含金量</li>
</ul>
<p>所以 5 座金矿的最优解应该是两者的最大值。</p>
<h3 id="建模"><a class="header-anchor" href="#建模"></a>建模</h3>
<p>金矿数量设为 n，工人数设为 w，金矿的含金量（按照金矿顺序）设为数组 g，金矿的用工量（按照金矿数量）设为数组 p，最优选择设为函数 F（n，w）</p>
<p>显然可以得出</p>
<pre><code class="language-python">g = [400, 500, 200, 300, 350]  # 金矿顺序下，各个金矿的含金量列表
p = [5, 5, 3, 4, 3]  # 金矿顺序下，各个金矿的用工数列表

F(5, 10) = max(F(4, 10), F(4, p[4]) + g[4])
</code></pre>
<h4 id="确定边界"><a class="header-anchor" href="#确定边界"></a>确定边界</h4>
<p>只有第一座金矿的时候，没得选：</p>
<ul>
<li><code>w &gt; p[0]</code>用工数（第一座金矿的用工数）：挖， <code>F(n, w) = g[0]</code></li>
<li><code>w &lt; p[0]</code>（第一座金矿的用工数）：不挖， <code>F(n, w) = 0</code></li>
</ul>
<h4 id="状态转移方程"><a class="header-anchor" href="#状态转移方程"></a>状态转移方程</h4>
<ul>
<li><code>F(n,w) = 0 (n&lt;=1, w&lt;p[0])</code></li>
<li><code>F(n,w) = g[0] (n==1, w&gt;=p[0])</code></li>
<li><code>F(n,w) = F(n-1,w) (n&gt;1, w&lt;p[n-1])</code></li>
<li><code>F(n,w) = max(F(n-1,w), F(n-1,w-p[n-1])+g[n-1]) (n&gt;1, w&gt;=p[n-1])</code></li>
</ul>
<p>动态规划的方法是自底向上的，这里需要输入两个维度的参数，实现自底向上比较复杂，可以使用表格分析：</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-11-18-133256.png" alt="image-20191118213256312"></p>
<p>表格的第一列表示金矿的顺序，也就是 n 的取值，表格的第一行是工人数，也就是 w 的取值。空白处表示给定金矿数量和工人数情况下，能获得的最大黄金量 <code>F(n, w)</code>。</p>
<p>第一个金矿：400 金，5 人</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-11-18-133719.png" alt="image-20191118213719332"></p>
<p>增加第二个金矿：500 斤，5 人</p>
<ul>
<li>
<p>w &lt; 5：</p>
<pre><code class="language-python">F(n, w) = F(n-1, w) = 0
</code></pre>
</li>
<li>
<p>w &gt;= 5：</p>
<pre><code class="language-python">F(n, w) = max(F(n-1, w), F(n-1, w-5)+ 500)
</code></pre>
</li>
</ul>
<p>所以第 5-9 个格子的值都是 500。第 10 个工人的时候，n=2，w=10，F(n-1, w) = 400, F(n-1, w-5) = 400, max(400, 400 + 500) = 900</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-11-18-134425.png" alt="image-20191118214425480"></p>
<p>以此类推可得：</p>
<p><img src="https://klause-blog-pictures.oss-cn-shanghai.aliyuncs.com/2019-11-18-134506.png" alt="image-20191118214505582"></p>
<p>可得规律，除第一行外，每一个格子都是前一行的一个或者两个格子推导得到，所以每次储存前一行结果就推导出下一行的结果。</p>
<h3 id="解决代码"><a class="header-anchor" href="#解决代码"></a>解决代码</h3>
<p>解决方法代码中的 pre_results、results 保存的就是行结果。</p>
<pre><code class="language-python">from typing import List


def F(n, w, g: List[int], p: List[int]) -&gt; int:
    &quot;&quot;&quot;
    问题：有一个国家发现了 5 座金矿，每座金矿的黄金储备量不同，需要挖坑的工人数也不同。参与挖矿工人的总数是 10 人。每座金矿要么全挖，要么不挖，不能派出一半人挖取一半金矿。要求用程序求解出，要想得到尽可能多的黄金，应该选择挖取那几座金矿？
    金矿产量数组 g = [400, 500, 200, 300, 350]
    金矿用工数数组 p = [5, 5, 3, 4, 3]
    :param n:金矿数量
    :param w:工人数
    :param g:金矿的黄金量
    :param p:金矿的用工量
    :return:可挖取得最大黄金量
    &quot;&quot;&quot;
    pre_results = []  # 储存前一次结果，索引是工人数，值是工人数条件下，可挖取的最大黄金量
    results = []  # 储存当前结果，索引是工人数，值是工人数条件下，可挖取的最大黄金量

    for i in range(w + 1):
        workers = p[0]
        if i &lt; workers:  # 只有第一座金矿时，工人数小于用工数，表示不开挖，所得黄金量为 0
            pre_results.insert(i, 0)
        else:  # 开挖时，所得黄金量为第一座金矿黄金量
            pre_results.insert(i, g[0])
    print(pre_results)  # 测试语句：打印查看只有第一座金矿，工人数与可获取的最大黄金量的关系

    for i in range(1, n):  # i 每增加 1 表示，按照金矿的顺序（g 列表）新增一座金矿
        results = []  # 每次遍历都初始化一次 results
        for j in range(w + 1):
            workers = p[i]  # workers 表示新增的这座金矿的用工数
            if j &lt; workers:  # 当工人数小于用工数时，表示新增的这座金矿不开挖
                results.insert(j, pre_results[j])
            else:  # 开挖新增的这座金矿
                tmp = max(pre_results[j], pre_results[j - workers] + g[i])
                results.insert(j, tmp)

        pre_results = results  # 将当前结果保存为上次结果，供下次新增金矿时使用
        print(results)  # 测试语句：每新增加一座金矿，打印查看一次工人数与最大黄金量的关系
    return results[w]


if __name__ == '__main__':
    g = [400, 500, 200, 300, 350]  # 金矿顺序下，各个金矿的含金量列表
    p = [5, 5, 3, 4, 3]  # 金矿顺序下，各个金矿的用工数列表
    result = F(5, 10, g, p)
    print(result)
</code></pre>
<p>动态规划的方法利用两层迭代，逐步推导最终结果。在外层的每一次迭代，表示按照金矿顺序增加一座金矿，也就是对表格每一行的迭代过程，都会保留上一行的结果数组 pre_results，并循环计算当前行的结果数组 results。</p>
<h3 id="时间复杂度-o-n-w"><a class="header-anchor" href="#时间复杂度-o-n-w"></a>时间复杂度 $O(n*w)$</h3>
<h3 id="空间复杂度-o-w"><a class="header-anchor" href="#空间复杂度-o-w"></a>空间复杂度 $O(w)$</h3>
<p>需要注意的是，当金矿只有 5 座的时候，动态规划的性能优势还没有体现出来。当有 10 座金矿，甚至更多金矿时，动态规划就明显具备了优势。</p>
<h3 id="拓展思考"><a class="header-anchor" href="#拓展思考"></a>拓展思考</h3>
<p>如果把题目改一下，总工人数变成 1000 人，每个金矿的用工数也相应增加，这时候该如何实现最优选择呢？</p>
<ul>
<li>动态规划方法
<ul>
<li>时间复杂度 $O(5*1000)$</li>
<li>空间复杂度 $O(1000)$</li>
</ul>
</li>
<li>简单递归方法
<ul>
<li>时间复杂度 $O(2^5)$  （5 座金矿）</li>
</ul>
</li>
</ul>
<p>显然 1000 个工人的时候，动态规划的性能远不如简单递归。</p>
<ul>
<li>动态规划方法的时间和空间都和 w 成正比</li>
<li>简单递归方法的时间却和 w 无关</li>
</ul>
<p>所以当工人数量很多的时候，动态规划反而不如递归。所以说，每一种算法都没有绝对的好与坏，关键看应用场景。</p>
<p>深入学习推荐，以动态规划为基础的算法还有：</p>
<ul>
<li>多重背包算法</li>
<li>迪杰特拉斯算法</li>
</ul>

<div id="gitalk-container"></div>
<script src="https://cdn.bootcss.com/blueimp-md5/2.12.0/js/md5.min.js"></script><link rel="stylesheet" href="https://unpkg.com/gitalk/dist/gitalk.css"><script src="https://unpkg.com/gitalk/dist/gitalk.min.js"></script>

		<script>
		var gitalkConfig = {"clientID":"9eb5bc3ac1e1ff3ddac0","clientSecret":"4b7ae28042282281295075c2bf0c97ff1791cfeb","repo":"HexoBlogComments","owner":"Annihilater","admin":["Annihilater"],"distractionFreeMode":false};
	    gitalkConfig.id = md5(location.pathname);
		var gitalk = new Gitalk(gitalkConfig);
	    gitalk.render("gitalk-container");
	    </script>
            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://www.klause.cn" rel="external nofollow noreferrer">湮灭星空</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://www.klause.cn/2019/11/19/suan-fa/dong-tai-gui-hua-ji-chu-pa-lou-ti-he-wa-jin-kuang-wen-ti/">https://www.klause.cn/2019/11/19/suan-fa/dong-tai-gui-hua-ji-chu-pa-lou-ti-he-wa-jin-kuang-wen-ti/</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="https://www.klause.cn" target="_blank">湮灭星空</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/markdown/">
                                    <span class="chip bg-color">markdown</span>
                                </a>
                            
                                <a href="/tags/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/">
                                    <span class="chip bg-color">动态规划</span>
                                </a>
                            
                                <a href="/tags/%E7%AE%97%E6%B3%95/">
                                    <span class="chip bg-color">算法</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">

<div id="article-share">
    
    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
        </div>
    </div>

    

    

    

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="fas fa-chevron-left"></i>&nbsp;上一篇</div>
            <div class="card">
                <a href="/2019/11/19/suan-fa/1143.zui-chang-gong-gong-zi-xu-lie-longestcommonsubsequence-jian-cheng-lcs-wen-ti/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/2.jpg" class="responsive-img" alt="1143.最长公共子序列（longestCommonSubsequence 简称LCS 问题）">
                        
                        <span class="card-title">1143.最长公共子序列（longestCommonSubsequence 简称LCS 问题）</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            1143.最长公共子序列（longestCommonSubsequence 简称LCS 问题）
问题
给定两个字符串 text1 和 text2，返回这两个字符串的最长公共子序列。
一个字符串的 子序列 是指这样一个新的字符串：它是由原字符
                        
                    </div>
                    <div class="publish-info">
                        <span class="publish-date">
                            <i class="far fa-clock fa-fw icon-date"></i>2019-11-19
                        </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Tech/" class="post-category">
                                    Tech
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E7%AE%97%E6%B3%95/">
                        <span class="chip bg-color">算法</span>
                    </a>
                    
                    <a href="/tags/%E6%9C%80%E9%95%BF%E5%85%AC%E5%85%B1%E5%AD%90%E4%B8%B2/">
                        <span class="chip bg-color">最长公共子串</span>
                    </a>
                    
                    <a href="/tags/LCS-%E9%97%AE%E9%A2%98/">
                        <span class="chip bg-color">LCS 问题</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/2019/11/02/markdown/jie-jue-jupyter-notebook-bu-neng-yun-xing-asyncio111/">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/8.jpg" class="responsive-img" alt="解决 Jupyter notebook 不能运行 asyncio">
                        
                        <span class="card-title">解决 Jupyter notebook 不能运行 asyncio</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            解决 Jupyter notebook 不能运行 asyncio
当 jupyter notebook 运行 asyncio 的时候回提示
RuntimeError: This event loop is already running


                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2019-11-02
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Tech/" class="post-category">
                                    Tech
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/jupyter-notebook/">
                        <span class="chip bg-color">jupyter notebook</span>
                    </a>
                    
                    <a href="/tags/jupyter-lab/">
                        <span class="chip bg-color">jupyter lab</span>
                    </a>
                    
                    <a href="/tags/asyncio/">
                        <span class="chip bg-color">asyncio</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>



<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>

    
<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>

    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            // headingsOffset: -205,
            headingSelector: 'h2, h3, h4, h5, h6'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4, h5, h6').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>


<script src="https://cdn.bootcss.com/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script>
    MathJax.Hub.Config({
        tex2jax: {inlineMath: [['$', '$'], ['\(', '\)']]}
    });
</script>


    <footer class="page-footer bg-color">
    <div class="container row center-align">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            <span id="year">年份</span>
            <a href="https://www.klause.cn" target="_blank">湮灭星空</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            &nbsp;<i class="fas fa-chart-area"></i>&nbsp;站点总字数:&nbsp;<span
                class="white-color">199.2k</span>&nbsp;字
            
            
            
            
            
            
            <span id="busuanzi_container_site_pv">
                |&nbsp;<i class="far fa-eye"></i>&nbsp;总访问量:&nbsp;<span id="busuanzi_value_site_pv"
                    class="white-color"></span>&nbsp;次
            </span>
            
            
            <span id="busuanzi_container_site_uv">
                |&nbsp;<i class="fas fa-users"></i>&nbsp;总访问人数:&nbsp;<span id="busuanzi_value_site_uv"
                    class="white-color"></span>&nbsp;人
            </span>
            
            <br>
            
            <span id="sitetime">载入运行时间...</span>
            <script>
                function siteTime() {
                    window.setTimeout("siteTime()", 1000);
                    var seconds = 1000;
                    var minutes = seconds * 60;
                    var hours = minutes * 60;
                    var days = hours * 24;
                    var years = days * 365;
                    var today = new Date();
                    var startYear = "2019";
                    var startMonth = "6";
                    var startDate = "28";
                    var startHour = "0";
                    var startMinute = "0";
                    var startSecond = "0";
                    var todayYear = today.getFullYear();
                    var todayMonth = today.getMonth() + 1;
                    var todayDate = today.getDate();
                    var todayHour = today.getHours();
                    var todayMinute = today.getMinutes();
                    var todaySecond = today.getSeconds();
                    var t1 = Date.UTC(startYear, startMonth, startDate, startHour, startMinute, startSecond);
                    var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
                    var diff = t2 - t1;
                    var diffYears = Math.floor(diff / years);
                    var diffDays = Math.floor((diff / days) - diffYears * 365);
                    var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
                    var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) /
                        minutes);
                    var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours -
                        diffMinutes * minutes) / seconds);
                    if (startYear == todayYear) {
                        document.getElementById("year").innerHTML = todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffDays + " 天 " + diffHours +
                            " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    } else {
                        document.getElementById("year").innerHTML = startYear + " - " + todayYear;
                        document.getElementById("sitetime").innerHTML = "本站已安全运行 " + diffYears + " 年 " + diffDays +
                            " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
                    }
                }
                setInterval(siteTime, 1000);
            </script>
            
            <br>
            
            <span id="icp"><img src="/medias/icp.png" style="vertical-align: text-bottom;" />
                <a href="http://www.beian.miit.gov.cn" target="_blank">皖ICP备18005729号-1</a>
            </span>
            
        </div>
        <div class="col s12 m4 l4 social-link social-statis">
    <a href="https://github.com/Annihilater" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:yanmiexingkong@gmail.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>





    <a href="https://twitter.com/" class="tooltipped" target="_blank" data-tooltip="关注我的Twitter: https://twitter.com/" data-position="top" data-delay="50">
        <i class="fab fa-twitter"></i>
    </a>







    <a href="https://www.zhihu.com/" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>

    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc("/" + "search.xml", 'searchInput', 'searchResult');
});
</script>
    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Global site tag (gtag.js) - Google Analytics -->


    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    
    <script async src="/libs/others/busuanzi.pure.mini.js"></script>
    

    

    

    

    

    
    <script type="text/javascript" src="/libs/background/ribbon-dynamic.js" async="async"></script>
    
    
    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
